;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Enterprise.Role", [])
        .controller("RoleCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE) {
            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {
                allChecked: false
            };
            $scope.submitted = false;
            $scope.dataList = [];
            $scope.detailInfo = {};
            $scope.menuList = [];
            $scope.curSelectedData = {};
            $scope.permissionCode = {
                add: 1
            };
            $scope.authCode = {};
            $scope.authCodeSelected = [];
            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                if (index == 0) {
                    initData();
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {};
                $scope.authCode = {};
                $scope.authCodeSelected = [];
            }

            function getDataList() {
                var service = "auth";
                var reqUrl = "/scepter/roles";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value, function (item) {
                        item.isChecked = false;
                    });
                    $scope.dataList = resp.value;
                });
            }

            $scope.search = function () {
                getDataList();
            };

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.delData = function (delType, roleId) {
                var service = "auth";
                var reqUrl = "/scepter/deleteRoles";
                var param = {};
                param.roleIds = [];

                if (delType === "single") {
                    param.roleIds.push(roleId);
                }

                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            param.roleIds.push($scope.dataList[i].id);
                        }
                    }
                    if (param.roleIds.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.roleIds).then(function (resp) {
                        if (resp.code !== 0) {
                            if (resp.code === 10) {
                                var tipMsg = "<div class='info-color m-b-sm'>" + resp.value + "</div>" + resp.message + "，请重新选择";
                                ybWidget.ShowMessage(tipMsg, MESG_TYPE.Warn, {isHtml: true});
                            } else {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            }
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.editData = function (role) {
                $scope.detailInfo = angular.copy(role);
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(1);
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "auth";
                var reqUrl = "/scepter/role";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/scepter/editRole";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            function getMenuList(service, reqUrl) {
                return ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return false;
                    }
                    return resp.value;
                });
            }

            function getAuthCode(service, reqUrl, param) {
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return false;
                    }
                    return resp.value;
                });
            }

            function setNodeStatus(menuList, authCode) {
                var menuList = {
                    children: menuList
                };
                angular.forEach(authCode, function (authItem) {
                    function setMenu(menuList) {
                        angular.forEach(menuList.children, function (item) {
                            if (authItem === item.id) {
                                item.isChecked = true;
                                return false;
                            }
                            if ((item.leaf === 0) && item.children.length > 0) {
                                setMenu(item);
                            }
                        });
                    }

                    setMenu(menuList);
                });
                checkTreeState();
            }

            function checkTreeState() {
                var menuList = {
                    children: $scope.menuList
                };

                function setTreeState(menuList) {
                    angular.forEach(menuList.children, function (item) {
                        if ((item.leaf === 0) && item.children.length > 0) {
                            setTreeState(item);
                            item.isChecked = checkNodeState(item.children);
                        }
                    });
                }

                setTreeState(menuList);
            }

            $scope.setPermission = function (item) {
                $scope.curSelectedData.roleId = item.id;
                $scope.curSelectedData.roleName = item.name;
                var service = "auth";
                var reqUrl = "/menu/shown";
                getMenuList(service, reqUrl).then(function (menuList) {
                    $scope.menuList = menuList;
                    $scope.changeTab(2);
                }).then(function () {
                    var service1 = "auth";
                    var reqUrl1 = "/scepter/getMenusAuths";
                    var param = {};
                    param.roleId = item.id;
                    getAuthCode(service1, reqUrl1, param).then(function (authCode) {
                        $scope.authCodeSelected = authCode.auths;

                        for (var i = 0; i < authCode.auths.length; i++) {
                            $scope.authCode[authCode.auths[i]] = true;
                        }

                        setNodeStatus($scope.menuList, authCode.menus);
                    });
                });
            };

            // 检验菜单是否全选，部分选择，未选
            function checkNodeState(menu) {
                var selectAll = false;
                var selectedCount = 0;
                var selectedHalf = 0;
                for (var i = 0, len = menu.length; i < len; i++) {
                    if (menu[i].isChecked === true) {
                        selectedCount++;
                    }
                    if (menu[i].isChecked === "notAll") {
                        selectedHalf++;
                    }
                }
                if (selectedCount === 0 && selectedHalf === 0) {
                    selectAll = false;
                } else if (selectedCount === menu.length) {
                    selectAll = true;
                } else {
                    selectAll = "notAll";
                }
                return selectAll;
            }

            function changeSubState(node) {
                var checked = node.isChecked;
                if ((node.leaf === 0) && node.children.length > 0) {
                    angular.forEach(node.children, function (item) {
                        item.isChecked = checked;
                        changeSubState(item);
                    })
                }
            }

            // 获取父节点
            function findParentNode(parentId) {
                var parentItem = [];
                var menuList = {
                    children: $scope.menuList
                };

                function findNode(list) {
                    angular.forEach(list.children, function (item) {
                        if (item.id === parentId) {
                            parentItem = item;
                        } else {
                            if ((item.leaf === 0) && item.children.length > 0) {
                                findNode(item);
                            }
                        }
                    });
                }

                findNode(menuList);
                return parentItem;
            }

            function changeParentState(parentId) {
                var parentItem = findParentNode(parentId);

                if ((parentItem.leaf === 0) && parentItem.children.length > 0) {
                    parentItem.isChecked = checkNodeState(parentItem.children);
                }

                if (parentItem.parentId !== 0) {
                    changeParentState(parentItem.parentId)
                }
            }

            // 改变被点击节点状态
            $scope.changeState = function (node) {
                // 设置子节点状态
                changeSubState(node);
                // 当此节点不是最高级时，改变父节点状态
                if (node.parentId !== 0) {
                    changeParentState(node.parentId);
                }
            };

            // 选择权限
            $scope.selectAuth = function (authId) {
                if ($scope.authCodeSelected.indexOf(authId) > -1) {
                    $scope.authCodeSelected.splice($scope.authCodeSelected.indexOf(authId), 1);
                } else {
                    $scope.authCodeSelected.push(authId);
                }
            };

            // 获取选中菜单
            function getCheckedItems() {
                var selectedItems = [];

                function findCheckedItem(list) {
                    angular.forEach(list, function (item) {
                        if (!!item.isChecked) {
                            selectedItems.push(item.id);
                        }
                        if ((item.leaf === 0) && (item.children.length > 0)) {
                            findCheckedItem(item.children);
                        }
                    })
                }

                findCheckedItem($scope.menuList);
                return selectedItems;
            }

            $scope.savePermission = function () {
                var service = "auth";
                var reqUrl = "/scepter/addMenusAuths";
                var param = {};
                param.roleId = $scope.curSelectedData.roleId;
                param.menuIds = getCheckedItems();
                param.authIds = $scope.authCodeSelected;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            (function () {
                getDataList();
            })();
        }])
    ;
})(window, window.angular);